package com.turbo.boot.crawler.spider.worker.impl.quota;

import com.alibaba.fastjson.JSON;
import com.turbo.boot.crawler.dao.dal.CrawlerResultDal;
import com.turbo.boot.crawler.dao.entity.CrawlerResultEntity;
import com.turbo.boot.crawler.spider.worker.BaseTurboApiCrawlerPageParser;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 描述
 *
 * @author wuyn
 * @since 2024/4/19
 */
@Slf4j
@Service("braemarScreenExchangeCrawlerPageParser")
public class BraemarScreenExchangeCrawlerPageParser extends BaseTurboApiCrawlerPageParser<BraemarScreenExchangeCrawlerPageParser.PageVo> {


    @Resource
    private CrawlerResultDal crawlerResultDal;

    @Override
    public void parse(PageVo pageVo) {
        log.info("获取数据:{}", pageVo.toString());

        // 解析封装 PageVo 对象
        if (StringUtils.isEmpty(pageVo.getName())) {
            return;
        }

        List<CrawlerResultEntity> batch = new ArrayList<>();
        for (Product product : pageVo.getProducts()) {
            CrawlerResultEntity entity = buildCrawlerResultEntity();
            entity.setQuotaCode(pageVo.getName() + "-" + product.getName());
            entity.setQuotaName(product.getName());
            entity.setQuotaValue(product.getPrice());
            entity.setCollectedAt(new Date());

            batch.add(entity);
        }

        if (CollectionUtils.isNotEmpty(batch)) {
            crawlerResultDal.insertBatch(batch);
        }

    }

//    public String getTargetUrl() {
//        return "https://blacksun-api.balticexchange.com/api/ticker";
//    }


    @Setter
    @Getter
    public static class PageVo {

        String name;
        List<Product> products;

        @Override
        public String toString() {
            return JSON.toJSONString(this);
        }
    }

    @Setter
    @Getter
    public static class Product {
        String id;
        String name;
        String price;
        String prevClose;
    }
}
